<template>
  <div>
    <div class="container">
      <el-form ref="form" :model="form" :rules="rules" label-width="210px">
        <el-form-item label="客户端名称" prop="clientName">
          <el-input
              v-model="form.clientName"
              placeholder="请填写客户端名称"
              clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="密钥过期时间" prop="clientSecretExpiresAt">
          <el-date-picker
              v-model="form.clientSecretExpiresAt"
              type="datetime"
              placeholder="选择日期时间"
              clearable
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="授权类型" prop="authorizedGrantType">
          <el-checkbox-group
              v-model="form.authorizedGrantType"
              placeholder="请填写授权类型"
          >
            <el-checkbox
                v-for="item in $enum.getMapItems('authorizedGrantType')"
                :key="item.value"
                :label="item.value"
            >{{ item.name }}
            </el-checkbox
            >
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="认证方法" prop="authenticationMethod">
          <el-checkbox-group
              v-model="form.authenticationMethod"
              placeholder="请填写认证方法"
          >
            <el-checkbox
                v-for="item in $enum.getMapItems('authenticationMethod')"
                :key="item.value"
                :label="item.value"
            >{{ item.name }}
            </el-checkbox
            >
          </el-checkbox-group>
        </el-form-item>
        <el-form-item
            v-if="form.redirectUri !== undefined && form.redirectUri.length > 0"
            v-for="(item, index) in form.redirectUri"
            :key="index"
            :label="index === 0 ? `重定向地址` : ''"
            :prop="`redirectUri[${index}]`"
            :rules="rules.redirectUri"
        >
          <el-input
              v-model="form.redirectUri[index]"
              :style="{ width: '300px', marginRight: '10px' }"
              placeholder="授权类型为授权码时填写"
              clearable
          ></el-input>
          <el-button
              v-if="index !== 0"
              type="danger"
              icon="el-icon-delete"
              circle
              size="small"
              @click="bindRemove('redirectUri', index)"
          ></el-button>
        </el-form-item>
        <el-form-item>
          <el-button
              type="primary"
              size="small"
              @click="bindAdd('redirectUri')"
          >新增重定向地址
          </el-button>
        </el-form-item>

        <el-form-item
            v-if="form.logoutRedirectUri !== undefined && form.logoutRedirectUri.length > 0"
            v-for="(item, index) in form.logoutRedirectUri"
            :key="index"
            :label="index === 0 ? `退出重定向地址` : ''"
            :prop="`logoutRedirectUri[${index}]`"
            :rules="rules.logoutRedirectUri"
        >
          <el-input
              v-model="form.logoutRedirectUri[index]"
              :style="{ width: '300px', marginRight: '10px' }"
              placeholder="请填写退出重定向地址"
              clearable
          ></el-input>
          <el-button
              v-if="index !== 0"
              type="danger"
              icon="el-icon-delete"
              circle
              size="small"
              @click="bindRemove('logoutRedirectUri', index)"
          ></el-button>
        </el-form-item>
        <el-form-item>
          <el-button
              type="primary"
              size="small"
              @click="bindAdd('logoutRedirectUri')"
          >新增退出重定向地址
          </el-button>
        </el-form-item>

        <el-form-item
            v-for="(item, index) in form.scope"
            :key="index"
            :label="index === 0 ? `权限范围` : ''"
            :prop="`scope[${index}]`"
            :rules="rules.scope"
        >
          <el-input
              v-model="form.scope[index]"
              :style="{ width: '300px', marginRight: '10px' }"
              placeholder="请填写权限范围"
              clearable
          ></el-input>
          <el-button
              v-if="index !== 0"
              type="danger"
              icon="el-icon-delete"
              circle
              size="small"
              @click="bindRemove('scope', index)"
          ></el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="small" @click="bindAdd('scope')"
          >新增权限范围
          </el-button
          >
        </el-form-item>

        <el-form-item label="客户端设置" prop="clientSetting">
          <el-input
              size="small"
              v-model="form.clientSetting"
              placeholder="请填写客户端设置"
              type="textarea"
              :autosize="{ minRows: 10, maxRows: 20 }"
              show-word-limit
              maxlength="999"
          ></el-input>
        </el-form-item>

        <el-form-item label="token设置" prop="tokenSetting">
          <el-input
              size="small"
              v-model="form.tokenSetting"
              placeholder="请填写token设置"
              type="textarea"
              :autosize="{ minRows: 10, maxRows: 20 }"
              show-word-limit
              maxlength="999"
          ></el-input>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input
              size="small"
              v-model="form.remark"
              placeholder="请填写备注"
              type="textarea"
              :autosize="{ minRows: 2, maxRows: 4 }"
              show-word-limit
              maxlength="99"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="small" @click="saveEdit"
          >保存
          </el-button
          >
          <el-button size="small" @click="goBack">取消</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-dialog
        :title="查看密匙"
        v-model="editVisible"
        width="50%"
        @closed="closed"
    >
      <el-form :model="formView" label-width="150px">
        <el-form-item label="客户端名称：">
          <div v-text="formView.clientName"></div>
        </el-form-item>
        <el-form-item label="客户端id：">
          <div v-text="formView.clientId"></div>
        </el-form-item>
        <el-form-item label="密匙：">
          <div v-text="formView.clientSecret"></div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="goBack">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script>
import {clientDetailApi, clientEditApi, clientSaveApi} from "../../../api/mgt/system/client";
import {createObjectBase, deepCopy} from "@/utils";

const objView = {
  //信息
  id: "",
  clientId: "",
  clientName: "",
  clientSecret: ""
};

const obj = {
  //信息
  id: "",
  clientName: "",
  clientSecretExpiresAt: "",
  remark: "",
  authorizationCodeValidity: 300,
  authorizedGrantType: [
    "password",
    "refresh_token",
    "authorization_code",
    "sms_code",
    "mail_code",
    "bind_code",
    "client_credentials",
  ],
  authenticationMethod: [
    "client_secret_basic",
    "client_secret_post",
  ],
  redirectUri: [""],
  logoutRedirectUri: [""],
  scope: [""],
  clientSetting: "",
  tokenSetting: "",
};
export default {
  data() {
    return {
      form: deepCopy(obj),
      formView: deepCopy(objView),
      editVisible: false,
      rules: {
        clientName: [
          {required: true, message: "请填写客户端名称", trigger: "change"},
          {max: 20, message: "长度不能超过20个字符", trigger: "change"},
        ],
        authorizedGrantType: [
          {required: true, message: "请填写授权类型", trigger: "change"},
        ],
        authenticationMethod: [
          {required: true, message: "请填写认证方法", trigger: "change"},
        ],
        redirectUri: [
          {max: 100, message: "长度不能超过100个字符", trigger: "change"},
        ],
        logoutRedirectUri: [
          {max: 100, message: "长度不能超过100个字符", trigger: "change"},
        ],
        scope: [
          {required: true, message: "请填写权限范围", trigger: "change"},
          {max: 10, message: "长度不能超过10个字符", trigger: "change"},
        ],
        clientSetting: [
          {required: true, message: "请填写客户端设置", trigger: "change"},
          {max: 499, message: "长度不能超过499个字符", trigger: "change"},
        ],
        tokenSetting: [
          {required: true, message: "请填写token设置", trigger: "change"},
          {max: 499, message: "长度不能超过499个字符", trigger: "change"},
        ],
        remark: [
          {max: 99, message: "长度不能超过99个字符", trigger: "change"},
        ],
      },
    };
  },
  methods: {
    // 编辑操作
    getDetail(id) {
      if (!id) {
        if (this.$refs.form != undefined) {
          this.$refs['form'].resetFields();
        }
      } else {
        clientDetailApi({id}).then((res) => {
          const data = deepCopy(res?.bizData);
          const {redirectUri, scope} = data;
          data.redirectUri = redirectUri;
          data.scope = scope;
          data.clientSetting = JSON.stringify(data.clientSetting, undefined, 2);
          data.tokenSetting = JSON.stringify(data.tokenSetting, undefined, 2);
          this.form = data;
        });
      }
    },
    saveEdit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          const data = createObjectBase(this.form, Object.keys(obj));
          const {id} = data;
          // 过滤空值
          data.redirectUri = data.redirectUri.filter((item) => item);
          data.logoutRedirectUri = data.logoutRedirectUri.filter((item) => item);
          data.scope = data.scope.filter((item) => item);
          data.clientSetting = JSON.parse(this.form.clientSetting);
          data.tokenSetting = JSON.parse(this.form.tokenSetting);
          const fn = id ? clientEditApi : clientSaveApi;
          fn(data).then((res) => {
            if (id) {
              this.goBack();
            } else {
              this.editVisible = true;
              this.formView = deepCopy(res?.bizData);
            }
          });
        } else {
          return false;
        }
      });
    },
    // 动态新增行
    bindAdd(key) {
      this.form[key].push("");
    },
    // 动态删除行
    bindRemove(key, index) {
      this.form[key].splice(index, 1);
    },
    goBack() {
      this.$router.goPage({
        path: "/client/page",
      });
    },
  },
  created() {
    const {id} = this.$route.query;
    this.getDetail(id);
  },
};
</script>
